package com.dj.dormitory.config;


import com.dj.dormitory.commonutils.JWTUtil;
import com.dj.dormitory.commonutils.ResultCode;
import com.dj.dormitory.entity.vo.SignVo;
import com.dj.dormitory.handler.DormitoryException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author DJ同学
 * @Date 2021/1/25 11:12
 * @Version 1.0
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String jwtToken = request.getHeader("token");

        SignVo signVo = JWTUtil.getSignByToken(request);
        if(signVo==null){
            throw new DormitoryException(ResultCode.ERROR,"token不合法或过期");
        }
        //下面设置的reponse添加的目的只是为了每次访问链接刷新一下token同时在前段的axios中添加store.setToken(response.headers.token)
        //可以不添加，
        //reponse 中设置token
//        String newToken = JWTUtil.getJwtToken(user.getId(),user.getUserName(),user.getType());
//        response.setHeader("Access-Control-Expose-Headers","token");
//        response.setHeader("token",newToken);

        request.setAttribute("userId",signVo.getUserId());
        request.setAttribute("userName",signVo.getUserName());
        request.setAttribute("type",signVo.getType());
        request.setAttribute("studentId",signVo.getStudentId());

        return true;
    }

}
